<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader :show-filter="true" title="用户管理" @search="onSearch" @reset-search="onResetSearch">
          <template #table-config>
            <a-space>
              <SortableTable class="ml-4" :columns="tableColumns" @update="onUpdateTable" />
              <TableConfig @update-border="onUpdateBorder" @update-striped="onUpdateStriped" @refresh="doRefresh" />
            </a-space>
          </template>

          <template #search-content>
            <TableSearchContent :conditionItems="conditionItems" />
          </template>
        </TableHeader>
      </template>
      <template #default>
        <a-table :loading="tableLoading" :bordered="{ wrapper: bordered, cell: bordered }"
          :stripe="(striped as boolean)" :data="dataList" :pagination="false" :row-key="rowKey"
          :row-class-name="rowClassNameFun">
          <template #columns>
            <a-table-column v-for="item of tableColumns" :data-index="(item.key as string)" v-bind="item"
              :key="item.key">
              <template v-if="item.key === 'index'" #cell="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template v-else-if="item.dictKey" #cell="{ record }">
                {{ dictValueToLabel(item.dictKey as string, record[item.key]) }}
              </template>
              <template v-else-if="item.key === 'optional'" #cell="{ record }">
                <a-button type="text" @click="onResetPassword(record)">重置密码</a-button>
                <a-button type="text" @click="onUpdateUser(record)">修改</a-button>
                <a-button type="text">启用</a-button>
                <a-button type="text">禁用</a-button>
                <a-button type="text">锁定</a-button>
                <a-button type="text">解锁</a-button>
                <a-button type="text" status="success">授权</a-button>
                <a-button type="text" status="danger">删除</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter :pagination="pagination" position="end" />
      </template>
    </TableBody>

    <FormModal v-model="form" width="70%" v-model:visible="showFormModal" :loading="formModalLoading"
      :title="formModalTitle" :submitButtonName="formSubmitButtonName" :formInfo="formInfo" :formRules="formRules"
      :okLoading="formOkLoading" @submitForm="onSubmitForm">
    </FormModal>
  </div>
</template>

<script setup lang="ts">
import UserService from '@/service/system/user'
import { usePagination, useRowKey, useTable, useTableColumn } from '@/hooks/table'
import { TablePropsType } from '@/types/components'
import { sortColumns } from '@/utils'
import { Message, Modal, FileItem } from '@arco-design/web-vue'
import { defineComponent, onMounted, reactive } from 'vue'
import useDict from '@/hooks/useDict'
import { buildFormRules, handleTree } from '@/utils'
import { FormModalFormInfoItem, FormItem } from '@/types/components'
import RoleService from '@/service/system/role'
import OrgService from '@/service/system/org'
import useUserStore from '@/store/modules/user'
import DownloadService from '@/service/system/download'

const userStore = useUserStore()
const showFormModal = ref(false)
const formModalLoading = ref(false)
const formOkLoading = ref(false)
const formModalTitle = ref('添加用户')
const searchAccount = ref()
const searchDescription = ref()
const searchRoleName = ref()
const roleListOptions = ref([])
const orgListOptions = ref([])
const formSubmitButtonName = '提交'
const conditionItems: Array<FormItem> = [
  {
    key: 'account',
    label: '账户',
    type: 'input',
    value: searchAccount,
  },
  {
    key: 'description',
    label: '所属部门',
    type: 'cascader',
    value: searchDescription,
    placeholder: '请选择所属部门',
    optionItems: orgListOptions,
    optionProps: {
      label: 'title',
      value: 'id'
    },
  },
  {
    key: 'roleName',
    label: '角色名称',
    type: 'input',
    value: searchRoleName,
  },
]
const form = ref({
  id: undefined,
  account: undefined,
  realName: undefined,
  mobile: undefined,
  roleId: undefined,
  orgIds: undefined,
  roleName: undefined,
  isEnabled: undefined,
  description: undefined,
  isLocked: undefined,
  type: undefined,
  orgModelWrapper: undefined,
  icon: undefined,
  userAvatarImage: undefined,
})
const formInfo: FormModalFormInfoItem[] = [
  {
    span: 12,
    type: 'input',
    field: 'account',
    label: '账号',
    placeholder: '请输入账号',
    feedback: true,
    disabled: true,
    rules: [
      {
        required: true,
        message: '请输入账号'
      }
    ]
  },
  {
    span: 12,
    type: 'input',
    field: 'realName',
    label: '姓名',
    placeholder: '请输入姓名'
  },
  {
    span: 12,
    type: 'input',
    field: 'mobile',
    label: '手机号码',
    placeholder: '请输入手机号码'
  },
  {
    span: 12,
    type: 'select',
    field: 'roleId',
    label: '角色',
    placeholder: '请选择角色',
    options: roleListOptions,
    optionProps: {
      label: 'name',
      value: 'id'
    }
  },
  {
    span: 12,
    type: 'cascader',
    field: 'orgIds',
    multiple: true,
    label: '指导关系',
    placeholder: '请选择指导关系',
    options: orgListOptions,
    optionProps: {
      label: 'title',
      value: 'id'
    },
    checkStrictly: true,
    rules: [
      {
        required: true,
        message: '请选择指导关系'
      }
    ],
  },
  {
    span: 12,
    type: 'cascader',
    field: 'description',
    label: '所属部门',
    placeholder: '请选择所属部门',
    options: orgListOptions,
    optionProps: {
      label: 'title',
      value: 'id'
    },
    checkStrictly: true,
  },
  {
    span: 12,
    type: 'userAvatar',
    field: 'userAvatarImage',
    uploadHeaders: { access_token: userStore.token },
    uploadAction: `${import.meta.env.VITE_BASH_URL}/jwcloud/system/uploadImage`,
    uploadSuccess: (fileItem: FileItem) => {
      console.log(fileItem, 'FileItem')
      form.value.icon = fileItem.response.data.url
      form.value.userAvatarImage = fileItem.url as any
    },
    label: '用户头像',
  },
]

const formRules = buildFormRules(formInfo)

RoleService.findRole({ pageSize: 10000 }).then(res => {
  if (res.code == 200) {
    roleListOptions.value = res.data
  }
})

OrgService.findOrg({}).then(res => {
  if (res.code == 200) {
    orgListOptions.value = handleTree(res.data)
  }
})
const onUpdateUser = async (record: any) => {
  form.value = record
  formModalTitle.value = '修改用户'
  showFormModal.value = true
  formModalLoading.value = true
  const [userResponse, downloadResponse] = await Promise.all([
    UserService.findUserDetail({ id: record.id }),
    record.icon ? DownloadService.downloadImage({ id: record.id, type: 'user' }) : Promise.resolve({ code: 200, data: false })
  ])
  formModalLoading.value = false
  if (userResponse.code == 200) {
    // 当前用户的角色列表
    const { roles, orgs, user } = userResponse.data
    form.value.realName = user.realName
    form.value.description = user.description
    form.value.roleId = (roles && roles.length > 0) ? roles[0].id : undefined
    form.value.orgIds = orgs.map((item: any) => item.id)
  }

  if (downloadResponse.code == 200 && downloadResponse.data) {
    form.value.userAvatarImage = downloadResponse.data
  }
}

const onSubmitForm = (formData: any) => {
  formOkLoading.value = true
  UserService.updateUser(form.value).then(res => {
    formOkLoading.value = false
    showFormModal.value = false
    doRefresh()
    if (res.code == 200) {
      Message.success('更新用户信息成功！')
    } else {
      Message.error('更新用户信息失败！')
    }
  })

}

const { dictValueToLabel } = useDict()
const table = useTable()
const {
  dataList,
  bordered,
  striped,
  tableLoading,
} = table
const pagination = usePagination(doRefresh)
const rowKey = useRowKey('id')
const tableColumns = reactive(
  useTableColumn([
    table.indexColumn,
    {
      title: '用户名',
      key: 'account',
      dataIndex: 'account',
    },
    {
      title: '姓名',
      key: 'realName',
      dataIndex: 'realName',
    },
    {
      title: '手机号码',
      key: 'mobile',
      dataIndex: 'mobile',
    },
    {
      title: '所属部门',
      key: 'description',
      dataIndex: 'description',
    },
    {
      title: '角色名称',
      key: 'roleName',
      dataIndex: 'roleName',
    },
    {
      title: '是否启用',
      key: 'isEnabled',
      dataIndex: 'isEnabled',
      dictKey: 'status',
    },
    {
      title: '是否锁定',
      key: 'isLocked',
      dataIndex: 'isLocked',
      dictKey: 'user_sts'
    },
    {
      title: '操作',
      key: 'optional',
      dataIndex: 'optional',
    },
  ])
)
function doRefresh() {
  UserService.getUserList({
    pageNum: pagination.page,
    pageSize: pagination.pageSize,
  }).then(res => {
    table.handleSuccess(res)
    pagination.setTotalSize(res.total)
  }).catch(console.log)
}
function onDeleteItem(item: any) {
  if (item) {
    Modal.confirm({
      content: '是否要删除此数据，删除后不恢复？',
      okText: '删除',
      onOk: () => {
        Message.success('模拟删除成功，参数为：' + item.id)
      },
    })
  }
}


const resetSearchForm = () => {
  searchAccount.value = undefined
  searchDescription.value = undefined
  searchRoleName.value = undefined
}

const onSearch = () => {
  doRefresh()
}

const onResetSearch = () => {
  resetSearchForm()
  pagination.page = 1
  pagination.pageSize = 10
  doRefresh()
}

// 重置密码按钮点击事件
function onResetPassword(record: any) {
  Modal.confirm({
    title: '提示',
    content: `是否将用户 ${record.account} 的密码重置为 ${record.account}123 ？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      UserService.resetPassword({
        id: record.id,
      }).then(res => {
        Message.success('密码重置成功！')
      }).catch(console.log)
    },
  })
}
function onUpdateTable(newColumns: Array<TablePropsType>) {
  sortColumns(tableColumns, newColumns)
}
function onUpdateBorder(isBordered: boolean) {
  table.bordered.value = isBordered
}
function onUpdateStriped(isStriped: boolean) {
  table.striped.value = isStriped
}
function rowClassNameFun(_record: any, index: number) {
  return index % 2 === 1 && table.striped.value ? 'table-striped' : null
}
onMounted(doRefresh)
</script>

<style lang="less" scoped></style>